package com.adopapa.ethexplorer.conf;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.adopapa.ethexplorer.utils.Tools;

/**
 * 动态切换数据库
 */
public class RedisTemplateManager<K, V> {

	private String host;
	private int port;

	private Map<Integer, RedisTemplate<K, V>> redisTemplates = //
			new HashMap<Integer, RedisTemplate<K, V>>();

	public RedisTemplateManager(String host, int port) {
		this.host = host;
		this.port = port;
	}

	/**
	 * 创建connetcionFactory
	 */
	private JedisConnectionFactory connectionFactory(int dbIndex) {
		
		RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
		configuration.setHostName(host);
		configuration.setPort(port);
		configuration.setDatabase(dbIndex);
		JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration);
		connectionFactory.afterPropertiesSet();
		
		return connectionFactory;
	}

	/**
	 * 创建redisTemplate
	 */
	private synchronized RedisTemplate<K, V> redisTemplate(int dbIndex) {

		RedisTemplate<K, V> redisTemplate = new RedisTemplate<K, V>();
		redisTemplate.setConnectionFactory(connectionFactory(dbIndex));
		StringRedisSerializer serializer = new StringRedisSerializer(Charset.forName("UTF-8"));
		redisTemplate.setKeySerializer(serializer);
		redisTemplate.setHashKeySerializer(serializer);
		redisTemplate.afterPropertiesSet();

		return redisTemplate;
	}

	/**
	 * 获取redisTemplate
	 */
	public synchronized RedisTemplate<K, V> getRedisTemplate(int dbIndex) {
		RedisTemplate<K, V> redisTemplate = redisTemplates.get(dbIndex);
		if (Tools.empty(redisTemplate)) {
			redisTemplate = redisTemplate(dbIndex);
			redisTemplates.put(dbIndex, redisTemplate);
		}
		return redisTemplate;
	}

}
